package com.xiashitech.agent.instrumentation.struts2.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.helper.calldepth.XSStruts2ProxyCallDepth;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Scope;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import static com.xiashitech.agent.instrumentation.struts2.XSStruts2ActionSingletons.instrumenter;
import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static net.bytebuddy.matcher.ElementMatchers.*;

public class XSStruts2ProxyExecuteInstrumentation implements TypeInstrumentation {

    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return named("org.apache.struts2.factory.StrutsActionProxy");//com.opensymphony.xwork2.DefaultActionProxy");//
    }

    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(
                isMethod()
                .and(named("execute"))
                .and(takesNoArguments())
                .and(isPublic())
                .and(returns(String.class)),
                XSStruts2ProxyExecuteInstrumentation.class.getName() + "$XSProxyExecuteAdvice");
    }

    public static class XSProxyExecuteAdvice {
        @Advice.OnMethodEnter(suppress = Throwable.class)
        public static void onEnter(
                @Advice.This Object proxy,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSStruts2ProxyExecuteInstrumentation");
            if (CacheStatus.cannotRun()) {
                return;
            }
            callDepth = CallDepth.forClass(XSStruts2ProxyCallDepth.class);
            if (callDepth.getAndIncrement() > 0) {
                return;
            }
            Context parentContext = currentContext();
            if (!instrumenter().shouldStart(parentContext, proxy)) {
                return;
            }
            parentContext = BaggageUtil.syncBaggage().build().storeInContext(parentContext);
            context = instrumenter().start(parentContext, proxy);
            context = BaggageUtil.syncBaggage().build().storeInContext(context);
            scope = context.makeCurrent();
            durationPrinter.printElapseDuration("XSProxyExecuteAdvice b");
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit(
                @Advice.Thrown Throwable throwable,
                @Advice.This Object proxy,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSStruts2ProxyExecuteInstrumentation");
            if (CacheStatus.cannotRun()) {
                return;
            }
            if (callDepth.decrementAndGet() > 0) {
                return;
            }
            if (scope == null) {
                return;
            }
            scope.close();

            UserRequest ur = UserRequest.builder().build();
            ur.setAnyObject(proxy);
            ur.setPosition("execute");
            instrumenter().end(context, null, ur, throwable);
            durationPrinter.printElapseDuration("XSProxyExecuteAdvice e");
        }
    }
}
